package com.gz.logistics.app;

import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.gz.logistics.R;
import com.gz.logistics.library.IOrder;
import com.gz.logistics.library.listener.SingleOrderDeliveryStatusChangeListener;
import com.gz.logistics.library.pojo.OrderDetail;
import com.gz.logistics.library.util.Constants;
import com.gz.logistics.util.NetworkUtil;
import com.gz.logistics.util.PayResult;
import com.gz.logistics.util.ShareUtil;
import com.gz.logistics.util.ToastUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

/**
 * 签收选择用户的支付方式确定信息
 * 杜志娟
 * 2016-02-26
 */
public class SelectPayTypeActivity extends Activity implements View.OnClickListener{
    private String TAG = SelectPayTypeActivity.class.getSimpleName();
    private OrderDetail orderInfo;
    private TextView pay_online;//在线支付
    private TextView pay_offline;//货到付款
    private RelativeLayout iv_selecttype;//货到付款支付方式
    private RadioButton rb_pos;//pos机支付
    private RadioButton rb_money;//微信支付
    private RadioButton rb_scan;//扫码支付
    private RadioButton rb_alipay;//支付宝
    private RadioButton card_dio1;//本行卡按钮
    private RadioButton card_dio2;//他行卡按钮
    private TextView yingshou_money;//应收金额
    private TextView shishou_money;//实收金额
    private Button btn_ok;//确定签收按钮
    private EditText tv_notes;//备注信息
    private MySingleOrderDeliveryStatusChangeListener mSingleOrderDeliveryStatusChangeListener;
    private int paytype = 1;//标识支付方式（在线支付，pos机，微信支付--原生4，扫码支付1，支付宝5）
    private final static int REQUEST_CONNECT_DEVICE = 1; // 跳转页面请求码
    private final static String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB"; // SPP服务UUID号
    private InputStream is; // 输入流，用来接收蓝牙数据
    BluetoothDevice _device = null; // 蓝牙设备
    BluetoothSocket _socket = null; // 蓝牙通信socket
    boolean bRun = true;
    boolean bThread = false;
    boolean flag = false, flag_time_cancel = false, flag_set_time = false;
    private RelativeLayout card_type;//卡类别（本行卡，他行卡）
    private RelativeLayout rl_transaction;//交易单号
    private RelativeLayout rl_card_num;//银行卡号
    private RelativeLayout rl_pos_num;//pos机编号
    private EditText dt_transaction;//交易流水号
    private EditText dt_card_num;//银行卡号
    private EditText dt_pos_num;//pos机编号
    private RelativeLayout back;
    private Button btn_pay;//立即支付按钮
    private Dialog mMenudialog;
    //private RefreshReceiver mRefreshReceiver;
    private AlertDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.select_paytype);

        orderInfo = (OrderDetail)getIntent().getSerializableExtra("orderdetail");//订单详情
        pay_online = (TextView)findViewById(R.id.pay_online);
        pay_offline = (TextView)findViewById(R.id.pay_offline);
        iv_selecttype = (RelativeLayout)findViewById(R.id.iv_selecttype);
        rb_pos = (RadioButton)findViewById(R.id.rb_pos);
        rb_pos.setOnClickListener(this);
        rb_money = (RadioButton)findViewById(R.id.rb_money);
        rb_money.setOnClickListener(this);
        rb_scan = (RadioButton)findViewById(R.id.rb_scan);
        rb_scan.setOnClickListener(this);
        yingshou_money = (TextView) findViewById(R.id.yingshou_money);
        shishou_money = (TextView)findViewById(R.id.shishou_money);
        btn_ok = (Button)findViewById(R.id.btn_ok);
        btn_ok.setOnClickListener(this);
        rb_alipay = (RadioButton) findViewById(R.id.rb_alipay);
        rb_alipay.setOnClickListener(this);
        tv_notes = (EditText)findViewById(R.id.tv_notes);
        card_type = (RelativeLayout) findViewById(R.id.card_type);
        card_dio1 = (RadioButton) findViewById(R.id.card_dio1);
        card_dio2 = (RadioButton) findViewById(R.id.card_dio2);
        rl_transaction = (RelativeLayout) findViewById(R.id.rl_transaction);
        rl_card_num = (RelativeLayout) findViewById(R.id.rl_card_num);
        rl_pos_num = (RelativeLayout) findViewById(R.id.rl_pos_num);
        dt_transaction = (EditText) findViewById(R.id.dt_transaction);
        dt_card_num = (EditText) findViewById(R.id.dt_card_num);
        dt_pos_num = (EditText) findViewById(R.id.dt_pos_num);
        btn_pay = (Button) findViewById(R.id.btn_pay);
        btn_pay.setOnClickListener(this);
        mSingleOrderDeliveryStatusChangeListener = new MySingleOrderDeliveryStatusChangeListener(this);

        if (orderInfo.getPay_type().equals("在线支付")){//在线支付
            paytype = 3;
            btn_pay.setVisibility(View.GONE);
            btn_ok.setVisibility(View.VISIBLE);
            pay_online.setBackgroundResource(R.drawable.bg_mall_frame_selected);
            pay_offline.setBackgroundResource(R.drawable.bg_mall_frame_unselected);

            //如果用pos支付就把此处注释代码放开
            /*iv_selecttype.setVisibility(View.GONE);
            card_type.setVisibility(View.GONE);
            rl_transaction.setVisibility(View.GONE);
            rl_card_num.setVisibility(View.GONE);
            rl_pos_num.setVisibility(View.GONE);*/

        }else{
            btn_ok.setVisibility(View.GONE);
            btn_pay.setVisibility(View.VISIBLE);
            pay_online.setBackgroundResource(R.drawable.bg_mall_frame_unselected);
            pay_offline.setBackgroundResource(R.drawable.bg_mall_frame_selected);
            //如果用pos支付就把此处注释代码放开
            /*iv_selecttype.setVisibility(View.VISIBLE);
            if (rb_pos.isChecked()==true){
                card_type.setVisibility(View.VISIBLE);
                rl_transaction.setVisibility(View.VISIBLE);
                rl_card_num.setVisibility(View.VISIBLE);
                rl_pos_num.setVisibility(View.VISIBLE);
                btn_pay.setVisibility(View.GONE);
                paytype = 2;
            }else */if (rb_money.isChecked()==true){
                card_type.setVisibility(View.GONE);
                rl_transaction.setVisibility(View.GONE);
                rl_card_num.setVisibility(View.GONE);
                rl_pos_num.setVisibility(View.GONE);
                btn_pay.setVisibility(View.VISIBLE);
                paytype = 4;
            }/*else{
                card_type.setVisibility(View.GONE);
                rl_transaction.setVisibility(View.GONE);
                rl_card_num.setVisibility(View.GONE);
                rl_pos_num.setVisibility(View.GONE);
                btn_pay.setVisibility(View.VISIBLE);
                paytype = 1;
            }*/
        }
        yingshou_money.setText(String.valueOf(orderInfo.getMoney()));
        shishou_money.setText(String.valueOf(orderInfo.getMoney()));
        back = (RelativeLayout) findViewById(R.id.back);
        back.setOnClickListener(this);

    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.back:
                finish();
                break;
            case R.id.btn_ok://确认签收按钮
                //调用单订单业务签收的方法
                int bank_flag = 0;//银行卡类别
                /*if(orderInfo.getPay_type().equals("货到付款")&&rb_pos.isChecked()==true){//判断是货到付款订单选中POS机闪付
                    if (card_dio1.isChecked()==true){
                        bank_flag = 1;
                    }else{
                        bank_flag = 2;
                    }
                    if(dt_transaction.getText().toString().trim().equals("")){
                        Toast.makeText(getApplicationContext(),"请输入交易号",Toast.LENGTH_LONG).show();
                    }else{
                        IOrder.getInstance().singalorderDeliveryStatusSign(orderInfo.getSn(), paytype, shishou_money.getText().toString().trim(), tv_notes.getText().toString(),bank_flag,dt_pos_num.getText().toString(),dt_card_num.getText().toString(),dt_transaction.getText().toString(),mSingleOrderDeliveryStatusChangeListener);
                    }

                }else{
                    if(orderInfo.getPay_type().equals("在线支付")){
                        paytype = 3;
                    }else{
                        paytype = 1;
                    }
                    IOrder.getInstance().singalorderDeliveryStatusSign(orderInfo.getSn(), paytype, shishou_money.getText().toString().trim(), tv_notes.getText().toString(),bank_flag,dt_pos_num.getText().toString(),dt_card_num.getText().toString(),dt_transaction.getText().toString(),mSingleOrderDeliveryStatusChangeListener);
                }*/
                paytype = 3;
                IOrder.getInstance().singalorderDeliveryStatusSign(orderInfo.getSn(), paytype, shishou_money.getText().toString().trim(), tv_notes.getText().toString(),bank_flag,dt_pos_num.getText().toString(),dt_card_num.getText().toString(),dt_transaction.getText().toString(),mSingleOrderDeliveryStatusChangeListener);

                break;
            case R.id.rb_money:
                paytype = 4;
                card_type.setVisibility(View.GONE);
                rl_transaction.setVisibility(View.GONE);
                rl_card_num.setVisibility(View.GONE);
                rl_pos_num.setVisibility(View.GONE);
                break;
            case R.id.rb_pos:
                paytype = 2;
                card_type.setVisibility(View.VISIBLE);
                rl_transaction.setVisibility(View.VISIBLE);
                rl_card_num.setVisibility(View.VISIBLE);
                rl_pos_num.setVisibility(View.VISIBLE);
                break;
            case R.id.rb_scan:
                paytype = 1;
                card_type.setVisibility(View.GONE);
                rl_transaction.setVisibility(View.GONE);
                rl_card_num.setVisibility(View.GONE);
                rl_pos_num.setVisibility(View.GONE);
                break;
            case R.id.rb_alipay:
                paytype = 5;
                card_type.setVisibility(View.GONE);
                rl_transaction.setVisibility(View.GONE);
                rl_card_num.setVisibility(View.GONE);
                rl_pos_num.setVisibility(View.GONE);
                break;
            case R.id.btn_pay:
                App.pay_sn = orderInfo.getSn();
                if (paytype==1){
                    //代表扫码支付
                    App.pay_wechat_type="7";
                    getcode();
                }else if(paytype==4){
                    //代表微信原生支付
                    App.pay_wechat_type="6";
                    Wechat();

                }else {//则代表支付宝支付
                    /*Runnable payRunnable = new Runnable() {

                        @Override
                        public void run() {
                            PayTask alipay = new PayTask(SelectPayTypeActivity.this);
                            Map<String, String>  result = alipay.payV2(orderInfo,true);
                            Log.i("chenghao", result.toString());
                            Message msg = new Message();
                            msg.what = 1;
                            msg.obj = result;
                            mHandler.sendMessage(msg);
                        }
                    };
                    // 必须异步调用
                    Thread payThread = new Thread(payRunnable);
                    payThread.start();*/
                }
                break;
        }

    }
    /**
     * 单订单业务签收回调接口
     */
    private class MySingleOrderDeliveryStatusChangeListener extends SingleOrderDeliveryStatusChangeListener {
        private SelectPayTypeActivity mOuter;

        public MySingleOrderDeliveryStatusChangeListener(SelectPayTypeActivity mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<SelectPayTypeActivity>(mOuter);
        }

        @Override
        public void onHasNotSignLogistic() {
            ToastUtils.showToast(mOuter.getApplicationContext(), "请先完成该订单的物流签收");

        }

        @Override
        public void onResponseSuccess() {
            OrderDetailActivity.btn_delivery_confirm.setVisibility(View.INVISIBLE);
            OrderDetailActivity.tv_delivery_status.setText("已签收");
            Intent broastIntent = new Intent(Define.ACTION_REFRESH_SHOPPING_CART);
            sendBroadcast(broastIntent);
            finish();
            ToastUtils.showToast(mOuter.getApplicationContext(), "业务签收成功");
        }

        @Override
        public void onNoNetWork() {
            ToastUtils.showToast(mOuter.getApplicationContext(),Define.MSG_NO_NETWORK);

        }

        @Override
        public void onResponseFailed() {
            ToastUtils.showToast(mOuter.getApplicationContext(),"业务签收失败");
        }
    }
    double app = 0;
    // 打开蓝牙并跳转到搜索界面
    public void openBluetooth(double hhe) {
        app = hhe;
        // 如果打开本地蓝牙设备不成功，提示信息，结束程序
        if (_bluetooth == null) {
            Toast.makeText(this, "无法打开手机蓝牙，请确认手机是否有蓝牙功能！", Toast.LENGTH_LONG)
                    .show();
        }
        if (_bluetooth.isEnabled() == false) { // 如果蓝牙服务不可用则提示
            // 打开蓝牙
            _bluetooth.enable();
            Toast.makeText(this, "正在开启蓝牙...", Toast.LENGTH_LONG).show();
        }
        // 如未连接设备则打开DeviceListActivity进行设备搜索
        if (_socket == null) {
            Intent serverIntent = new Intent(this, DeviceListActivity.class); // 跳转页面
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE); // 意图对象和请求码
        } else {
            System.out.println("_bluetooth.getState()" + _bluetooth.getState());

            // 关闭连接socket
            try {

                is.close();
                _socket.close();
                _socket = null;
                flag = false; // 连接标志位

            } catch (Exception e) {
            }

        }
    }
    // 获取本地蓝牙
    BluetoothAdapter _bluetooth = BluetoothAdapter.getDefaultAdapter();
    public void connect(View v) {
        openBluetooth(0);
    }

    /**
     * 数据回调
     * @param requestCode
     * @param resultCode
     * @param data
     */
   /* @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CONNECT_DEVICE: // 连接结果，由DeviceListActivity设置返回
                // 响应返回结果
                if (resultCode == Activity.RESULT_OK) { // 连接成功，由DeviceListActivity设置返回
                    // MAC地址，由DeviceListActivity设置返回
                    String address = data.getExtras().getString(
                            DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                    // 得到蓝牙设备
                    _device = _bluetooth.getRemoteDevice(address);
                    // 用服务号得到socket
                    try {
                        _socket = _device.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));
                    } catch (IOException e) {
                        Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT).show();
                    }
                    // 连接socket
                    try {
                        _socket.connect();
                        Toast.makeText(this, "连接" + _device.getName() + "成功！",
                                Toast.LENGTH_SHORT).show();
                        // btn.setText("断开");
                        flag = true; // 连接标志位
                        sendData(app);

                    } catch (IOException e) {
                        try {
                            Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT)
                                    .show();
                            _socket.close();
                            _socket = null;
                        } catch (IOException ee) {
                            Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT)
                                    .show();
                        }

                        return;
                    }

                    // 打开接收线程
                    try {
                        is = _socket.getInputStream(); // 得到蓝牙数据输入流

                    } catch (IOException e) {
                        Toast.makeText(this, "接收数据失败！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (bThread == false) {
                        ReadThread.start();
                        bThread = true;
                    } else {
                        bRun = true;
                    }
                } else {
                    flag = false; // 连接标志位
                }

        }
    }*/
    // 消息处理队列
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0://交易成功
                    m = (Map) msg.obj;
                    /**
                     * 调用签收订单的接口
                     * orderInfo.getSn()订单编号
                     * paytype支付方式
                     * shishou_money.getText().toString().trim() 交易金额
                     */
                    String notes = tv_notes.getText()+";POS机终端编号:"+m.get("terminalNum")+";卡种类："+m.get("cardType")+";参考号："+m.get("consult")+";POS机凭证号"+m.get("voucher");
                    break;
                case 1:
                    m = (Map) msg.obj;
                    //res = "未签到";
                    break;

                case 2://交易取消
                    m = (Map) msg.obj;
                    ToastUtils.showToast(getApplication(), "交易取消");
                    break;

            }

        }
    };
    // 接收数据线程
    Thread ReadThread = new Thread() {
        int num = 0;
        byte[] buffer = new byte[1024];
        byte[] buffer_new = new byte[1024];
        int parkLen;
        byte check;
        String packtype;
        String packManey;
        String packCode;
        public void run() {
            // 接收线程
            while (true) {
                try {
                    try {
                        sleep(100);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if (is.available() > 0) {
                        // 读取取标准
                        num = is.read(buffer_new, 0, 1); // 读入数据
                        if (buffer_new[0] == 0x02) {
                            try {
                                sleep(5000);
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            // 读取长度
                            num = is.read(buffer_new, 0, 2);
                            parkLen = ((buffer_new[0] >> 4) & 0x0F) * 1000;
                            parkLen += ((buffer_new[0]) & 0x0F) * 100;
                            parkLen += ((buffer_new[1] >> 4) & 0x0F) * 10;
                            parkLen += (buffer_new[1]) & 0x0F;
                            check = buffer_new[0];
                            check ^= buffer_new[1];
                            // 读取包数据
                            num = is.read(buffer, 0, parkLen);
                            for (int count = 0; count < parkLen; count++) {
                                check ^= buffer[count];
                            }
                            // 读取结束和校验
                            is.read(buffer_new, 0, 2);
                            if (buffer_new[0] == 0x03) {
                                check ^= buffer_new[0];
                                if (check == buffer_new[1]) {
                                    System.out.println("check Ok");
                                    packtype = new String(buffer, 0, 2);// 数据包类型码
                                    if (packtype.equals("03")) {

                                        packCode = new String(buffer, 2, 2);// 交易类型码
                                        if(packCode.equals("A1"))
                                            packCode="消费";
                                        if(packCode.equals("D1"))
                                            packCode="签到";
                                        packManey = new String(buffer, 4, 12);// 交易金额
                                        String packMoney = String.valueOf((Double.parseDouble(packManey))/100);
                                        String commodityCode = new String( buffer, 16, 15);// 商户编号 ()
                                        String posMum = new String(buffer, 31,4);// POS顺序号 ()
                                        String terminalNum = new String(buffer,35, 8);// 终端编号
                                        String voucher = new String(buffer, 43,6);// POS凭单号
                                        String idCard = new String(buffer, 73,21);// 卡 号()
                                        String operator = new String(buffer, 118, 5);// 操作员号
                                        String cardType = new String(buffer,168, 12);// 卡种类（发卡行名称）
                                        String consult = new String(buffer, 49,12);// 参考号
                                        map.put("consult", consult.trim());// 参考号
                                        map.put("res", "成功");//结果
                                        map.put("packtype", packtype);// 数据包类型码
                                        map.put("packCode", packCode);// 交易类型码
                                        map.put("packMoney", packMoney);// 交易金额
                                        map.put("commodityCode", commodityCode.trim());// 商户编号 ()
                                        map.put("posMum", posMum.trim());// POS顺序号 ()
                                        map.put("terminalNum", terminalNum);// 终端编号
                                        map.put("voucher", voucher);// POS凭单号
                                        map.put("idCard", idCard.trim());// 卡 号()
                                        map.put("cardType", cardType);// 卡种类（发卡行名称）
                                        map.put("operator",operator);//操作员
                                        Message msg = handler.obtainMessage();
                                        msg.obj = map;
                                        msg.what = 0;
                                        handler.sendMessage(msg);
                                    } else if (packtype.equals("04")) {
                                        packManey = new String(buffer,2,2);
                                        if (packManey.equals("04")) {

                                            //res = "未签到";
                                            Message msg = handler.obtainMessage();
                                            map.put("res", "未签到");
                                            msg.obj = map;
                                            msg.what = 1;
                                            handler.sendMessage(msg);
                                        } else if (packManey.equals("05")) {

                                            Message msg = handler.obtainMessage();
                                            map.put("res", "取消交易");
                                            msg.obj = map;
                                            msg.what = 2;
                                            handler.sendMessage(msg);
                                        }
                                    }

                                }
                            }

                        }

                    }
                } catch (IOException e) {
                }
            }
        }
    };
    private Map<String, String> map = new HashMap<String, String>();

    protected static Map<String, String> m = new HashMap<String, String>();

    // 发送数据
    public void sendData(View v) {
        sendData(100);
    }

    public void sendData(double money) {
        // String money = etText.getText().toString().trim();

        String strMoney = String.valueOf(money);
        if (strMoney.length() > 0) {

            // 将参数转为byte
            byte[] bos = { 0x02, 0x00, 0x16, 0x30, 0x30, 0x41, 0x31, 0x30,
                    0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
                    0x31, 0x03, 0x64 };
            byte[] moneyByte = String.valueOf((int)(money*100)).getBytes();

            System.arraycopy(moneyByte, 0, bos, bos.length - 2
                    - moneyByte.length, moneyByte.length);
            // 校验
            byte check = bos[1];
            for (int i = 1; i < bos.length - 2; i++) {
                check ^= bos[i + 1];
            }
            bos[bos.length - 1] = check;
            if (flag == true) {

                try {
                    // 获取输出流对象
                    OutputStream os = _socket.getOutputStream();
                    // 发送消息
                    os.write(bos);
                    // Toast.makeText(this, "数据发送成功", 0).show();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(this, "蓝牙未连接", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(this, "请输入数据", Toast.LENGTH_LONG).show();
        }
    }

    // 关闭程序掉用处理部分
    public void onDestroy() {
        super.onDestroy();
        if (_socket != null) // 关闭连接socket
            try {
                _socket.close();
            } catch (IOException e) {
            }
    }

    /**
     * 交易返回结果
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode
            , int resultCode, Intent data) {
        if(requestCode == 0){
            switch(resultCode) {
                case Activity.RESULT_CANCELED://交易失败。在onActivityResult的intent里附带StringExtra – “reason”表示失败原因，可用于显示或者记录。
                    String reason = data.getStringExtra("detail");
                    Toast.makeText(this, reason, Toast.LENGTH_LONG).show();
                    break;
                case Activity.RESULT_OK://交易成功
                    /*Log.i("duzhijuan",data.getStringExtra("traceNo"));//交易成功的流水号
                    Log.i("duzhijuan",data.getStringExtra("terminalName"));//交易使用的终端（APOS不返回)
                    Log.i("duzhijuan",data.getStringExtra("amount"));//交易金额
                    Log.i("duzhijuan",data.getStringExtra("refNo"));//交易参考号
                    Log.i("duzhijuan",data.getStringExtra("date"));//交易日期*/
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     *
     * @param appid
     * @param partnerid
     * @param prepay_id
     * @param nonce_str
     * @param time
     * @param sign
     *
     * 微信支付
     */
    public void wechatpay(String appid,String partnerid,String prepay_id,String nonce_str,String time,String packagename,String sign){
        IWXAPI api;
        api= WXAPIFactory.createWXAPI(SelectPayTypeActivity.this,null);
        api.registerApp(appid);

        PayReq req = new PayReq();
        req.appId= appid;
        req.partnerId=partnerid;
        req.prepayId=prepay_id;
        req.nonceStr=nonce_str;
        req.timeStamp=time;
        //req.packageValue="Sign=WechatPay";
        req.packageValue=packagename;
        req.sign=sign;
        // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
        api.sendReq(req);
        finish();
    }

    public void Wechat() {
        if (NetworkUtil.isNetworkConnected(SelectPayTypeActivity.this)) {
            dialog = new AlertDialog.Builder(SelectPayTypeActivity.this, R.style.Transparcent_NoTitle).create();
            View dialogView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.custom_diglog, null);
            dialog.setCanceledOnTouchOutside(false);
            dialog.setView(dialogView, 0, 0, 0, 0);
            dialog.show();
            String url = Constants.URL_HOST+"/android_store/generate_wx_bill";
            RequestParams params = new RequestParams(url);
            params.addParameter("app_body", "考拉物流签收订单");
            params.addParameter("total_fee", doubleToString(yingshou_money.getText().toString()));//doubleToString(yingshou_money.getText().toString())
            params.addParameter("out_trade_no", orderInfo.getSn());

            Log.i("dzj", params + "");

            x.http().get(params, new Callback.CommonCallback<String>() {
                @Override
                public void onCancelled(CancelledException arg0) {
                }

                @Override
                public void onError(Throwable arg0, boolean arg1) {
                }

                @Override
                public void onFinished() {
                }

                @Override
                public void onSuccess(String result) {
                    try {
                        JSONObject jsonObject = new JSONObject(result.toString());
                        if ("0".equals(jsonObject.getString("ret"))){
                            wechatpay(jsonObject.getJSONObject("result").getString("appid"),
                                      jsonObject.getJSONObject("result").getString("partnerid"),
                                      jsonObject.getJSONObject("result").getString("prepayid"),
                                      jsonObject.getJSONObject("result").getString("noncestr"),
                                      jsonObject.getJSONObject("result").getString("timestamp"),
                                      jsonObject.getJSONObject("result").getString("package"),
                                      jsonObject.getJSONObject("result").getString("sign"));
                        }else{
                            Toast.makeText(SelectPayTypeActivity.this,jsonObject.getString("msg"),Toast.LENGTH_LONG).show();
                            dialog.dismiss();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            });
        } else {
            Toast.makeText(SelectPayTypeActivity.this, "请检查您的网络状况...", Toast.LENGTH_SHORT).show();
        }
    }



    private void ScanDialog(final String url) {
        dialog.dismiss();
        mMenudialog = new Dialog(SelectPayTypeActivity.this, R.style.DialogTheme);
        View dialogView = LayoutInflater.from(SelectPayTypeActivity.this).inflate(R.layout.qrcode_dialog, null);
        final ImageView img = (ImageView) dialogView.findViewById(R.id.img);
        /*ImageOptions imageOptions = new ImageOptions.Builder()
                .setIgnoreGif(false)//是否忽略gif图。false表示不忽略。不写这句，默认是true
                .setImageScaleType(ImageView.ScaleType.CENTER_CROP)
                .setFailureDrawableId(R.drawable.ic_qr_code)
                .setFailureDrawableId(R.drawable.ic_qr_code)
                .setCrop(true)
                .build();
        x.image().bind(img,url,imageOptions);*/
         Bitmap mBitmap = CodeUtils.createImage(url, 400, 400, null);
        img.setImageBitmap(mBitmap);
        Button btn_confirm = (Button) dialogView.findViewById(R.id.btn_confirm);
        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMenudialog.dismiss();
                //Wechatresult();
                finish();
            }
        });
        dialogView.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMenudialog.dismiss();
            }
        });
        mMenudialog.setContentView(dialogView);
        mMenudialog.setCancelable(false);
        mMenudialog.setCanceledOnTouchOutside(false);
        mMenudialog.show();

    }
    public void getcode() {
        if (NetworkUtil.isNetworkConnected(SelectPayTypeActivity.this)) {
            dialog = new AlertDialog.Builder(SelectPayTypeActivity.this, R.style.Transparcent_NoTitle).create();
            View dialogView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.custom_diglog, null);
            dialog.setCanceledOnTouchOutside(false);
            dialog.setView(dialogView, 0, 0, 0, 0);
            dialog.show();
            String url = Constants.URL_HOST+"/android_store/generate_wx_ewm";
            RequestParams params = new RequestParams(url);
            params.addParameter("app_body", "微信扫码支付");
            params.addParameter("out_trade_no", App.pay_sn);
            params.addParameter("total_fee",doubleToString(yingshou_money.getText().toString()));//doubleToString(yingshou_money.getText().toString())
            params.addParameter("product_id",orderInfo.getProductInfos().size()==0?"1":orderInfo.getProductInfos().get(0).getProduct_id());
            Log.i("dzj", params + "");
            x.http().get(params, new Callback.CommonCallback<String>() {
                @Override
                public void onCancelled(CancelledException arg0) {
                    dialog.dismiss();
                }

                @Override
                public void onError(Throwable arg0, boolean arg1) {
                    dialog.dismiss();
                }


                @Override
                public void onFinished() {
                    dialog.dismiss();
                }

                @Override
                public void onSuccess(String result) {
                    try {
                        JSONObject jsonObject = new JSONObject(result.toString());
                        if ("0".equals(jsonObject.getString("ret"))){
                            Log.i("dzj",jsonObject.getString("result"));
                            ScanDialog(jsonObject.getString("result"));
                        }else{
                            Toast.makeText(SelectPayTypeActivity.this,jsonObject.getString("msg"),Toast.LENGTH_LONG).show();
                            dialog.dismiss();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            });
        } else {
        }
    }

    public void Wechatresult() {
        if (NetworkUtil.isNetworkConnected(SelectPayTypeActivity.this)) {
            String url = Constants.URL_HOST+"/android_store/order_query";
            RequestParams params = new RequestParams(url);
            params.addParameter("out_trade_no", App.pay_sn);
            params.addParameter("receiveType",App.pay_wechat_type);
            params.addParameter("uid", ShareUtil.getstringvalue(SelectPayTypeActivity.this,"uid") );
            Log.i("dzj", params + "");
            x.http().get(params, new Callback.CommonCallback<String>() {
                @Override
                public void onCancelled(CancelledException arg0) {
                }

                @Override
                public void onError(Throwable arg0, boolean arg1) {
                }

                @Override
                public void onFinished() {
                }

                @Override
                public void onSuccess(String result) {
                    try {
                        JSONObject json = new JSONObject(result.toString());
                        if ("0".equals(json.getString("ret"))){

                        }else{
                            Toast.makeText(SelectPayTypeActivity.this,"支付成功,数据操作失败,请联系客服处理",Toast.LENGTH_LONG).show();
                        }
                        finish();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
        }
    }
    public static String doubleToString(String num){
        double mydouble=Double.parseDouble(num);
        int index=(int) (mydouble*100);
        return index+"";
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            @SuppressWarnings("unchecked")
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            /**
             对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
             */
            String resultInfo = payResult.getResult();// 同步返回需要验证的信息
            String resultStatus = payResult.getResultStatus();
            Log.i("chenghao","支付宝返回:"+resultStatus);
            // 判断resultStatus 为9000则代表支付成功
            if (TextUtils.equals(resultStatus, "9000")) {
                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                Toast.makeText(SelectPayTypeActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
            } else {
                // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                Toast.makeText(SelectPayTypeActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
            }
        };
    };
}
